package com.abigdreamer.im.server.sound;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 */
public class SoundPlay {

	private File file =null;
	private AudioInputStream ais;
	private SourceDataLine line;
	private AudioFormat baseFormat;
	private static final int BUFFER_SIZE = 4000 * 4;

	private SourceDataLine getLine(AudioFormat audioFormat) {
		SourceDataLine res = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class,
				audioFormat);
		try {
			res = (SourceDataLine) AudioSystem.getLine(info);
			res.open(audioFormat);
		} catch (Exception e) {
		}
		return res;
	}

	private void play() throws UnsupportedAudioFileException,
			LineUnavailableException, IOException {
		
		ais = AudioSystem.getAudioInputStream(file);
		baseFormat = ais.getFormat();

		line = getLine(baseFormat);
		line.start();
		int inBytes = 0;
		byte[] audioData = new byte[BUFFER_SIZE];
		while (inBytes != -1) {
			inBytes = ais.read(audioData, 0, BUFFER_SIZE);
			if (inBytes >= 0) {
				int outBytes = line.write(audioData, 0, inBytes);
			}
		}
	}

	public static void playStartSound(){
		playWav("XpStart.wav");
	}
	public static void playClosedSound(){
		playWav("XpClosed.wav");
	}
	public static void playNotifySound(){
		playWav("notify.wav");
	}
	
	public static void playWav(String filename){
		SoundPlay play=new SoundPlay();
		String path=SoundPlay.class.getPackage().getName().replace(".", "/");
		File file=new File(SoundPlay.class.getResource("/").getPath().replace("file:\\", "") + "/"+path+"/"+filename);
		play.setFile(file);
		 try {
			play.play();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
	
	public static void main(String[] args) {
		SoundPlay.playNotifySound();
	}
}
